import {login,logout,loginChangeOrg} from '@/api/login'
import {setToken, getToken, setLoginUser, getLoginUser, apiResult} from '@/libs/util'
import MapInfo from "@/view/Home/map/maptools/data/MapInfo";
import Vuex from "vuex";

export default {
  state: {
    //loginName: '',
    fullName: '',
    userName: '',
    userCode: '',
    userId: '',
    avatarImgPath: '',
    token: getToken(),
    access: '',
    hasGetInfo: false,
    unreadCount: 0,
    messageUnreadList: [],
    messageReadedList: [],
    messageTrashList: [],
    messageContentStore: {},
    //organizations:[{code: '00111',shortName:'总部--1212',selected:true,disabled:true},{code: '100000',shortName:'华北事业部',selected:false,disabled:false}]
    organizations:[],
    userMessage:[],
    deviceStatus:{deviceCode:null,status:0}, //0下线，1上线
    userMessageCount:0,
    userInfo: {},
    eventSource:null,
    mediaReplayFinish:{deviceCode:null,finished:false}, //设备code,回放结束
/*    {
      loginName: '',
      fullName: '',
      userName: '',
      userCode: '',
      userId: '',
      organizations:[],
    }*/
  },
  mutations: {
    setMediaReplayFinish(state, data){
      console.log(">>>>>>> setMediaReplayFinish.data=%o",data);
      state.mediaReplayFinish = data
    },
    setDeviceStatus(state, data){
      state.deviceStatus = data
    },
    setLoginName(state, loginName) {
      state.loginName = loginName
    },
    setFullName(state, fullName) {
      state.fullName = fullName
    },
    setUserCode(state, userCode) {
      state.userCode = userCode
    },
    setOrganizations(state, organizations) {
      state.organizations = organizations
    },
    setAvatar (state, avatarPath) {
      state.avatarImgPath = avatarPath
    },
    setUserId (state, id) {
      state.userId = id
    },
    setUserName (state, name) {
      state.userName = name
    },
    setAccess (state, access) {
      state.access = access
    },
    setToken (state, token) {
      state.token = token
      setToken(token)
    },
    setHasGetInfo (state, status) {
      state.hasGetInfo = status
    },
    setMessageCount (state, count) {
      state.unreadCount = count
    },
    setMessageUnreadList (state, list) {
      state.messageUnreadList = list
    },
    setMessageReadedList (state, list) {
      state.messageReadedList = list
    },
    setMessageTrashList (state, list) {
      state.messageTrashList = list
    },
    updateMessageContentStore (state, { msg_id, content }) {
      state.messageContentStore[msg_id] = content
    },
    moveMsg (state, { from, to, msg_id }) {
      const index = state[from].findIndex(_ => _.msg_id === msg_id)
      const msgItem = state[from].splice(index, 1)[0]
      msgItem.loading = false
      state[to].unshift(msgItem)
    },
    addUserMessage(state,message){
      state.userMessage.push(message);
    },
    clearUserMessage(state){
      state.userMessage=[];
    },

    setUserInfo(state,userInfo){
      state.userInfo = userInfo;
      setLoginUser(userInfo);
    },

    setEventSource(state,eventSource){
      state.eventSource = eventSource;
    }

  },
  getters: {
    getMediaReplayFinish:state=>state.mediaReplayFinish,
    getDeviceStatus:state=>state.deviceStatus,
    getOrganizations: state=>state.organizations,
    getLoginName: state => state.loginName,
    getFullName: state => state.fullName,
    getUserName: state => state.userName,
    messageUnreadCount: state => state.messageUnreadList.length,
    messageReadedCount: state => state.messageReadedList.length,
    messageTrashCount: state => state.messageTrashList.length,
    getUserMessage: state => state.userMessage,
    userMessageCount:state => state.userMessage.length,
    getUserInfo:state =>{
      return getLoginUser();
    }

  },
  actions: {
    // 登录
    login({ commit }, loginInfo) {
/*      console.log("login.this = %o",this);
      console.log("login.this.sse = %o",this._actions.sse);
      console.log("login.this.eventSource = %o",this.state);*/
      //this.sseSource
      const sseFun = this._actions.sse;
      const loginName = loginInfo.loginName.trim()
      return new Promise((resolve, reject) => {
        login(
          loginName,
          loginInfo.password,
          loginInfo.sessionId,
          loginInfo.verifyCode,
        ).then(res => {
          //console.log(">>>>>> login: res=%o",res);
          if (res.status === 200) {
            apiResult(res.data,false,result=>{
              let userInfo=result.data.userInfo;
              //console.log(">>>>>> userInfo: res=%o",res.data.data.userInfo);
              commit('setLoginName', loginName);
              commit('setUserName', userInfo.userName);
              commit('setToken', result.data.token)
              commit('setUserCode', userInfo.userCode);
              commit('setFullName', userInfo.fullName);
              commit('setOrganizations', userInfo.organizations);
              commit('setUserInfo',userInfo);
              //初如化地图参数
              new MapInfo().setFromApi();
              resolve(result.data.token)
            },err=>{
              reject({code:err.code,msg:err.msg});
            })
            /*if (res.data.code === 0) {
              let userInfo=res.data.data.userInfo;
              //console.log(">>>>>> userInfo: res=%o",res.data.data.userInfo);
              commit('setLoginName', loginName);
              commit('setUserName', userInfo.userName);
              commit('setToken', res.data.data.token)
              commit('setUserCode', userInfo.userCode);
              commit('setFullName', userInfo.fullName);
              commit('setOrganizations', userInfo.organizations);
              commit('setUserInfo',userInfo);
              //初如化地图参数
              new MapInfo().setFromApi();
              resolve(res.data.data.token)
            } else {
              console.log(res.data.msg);
              //const errCode =  "msg_"+res.data.code;
              reject({code:res.data.code,msg:res.data.msg});
              //this.$router.push('/login');
            }*/
          }else{
            this.$Message.error(res.message);
          }
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 退出登录
    logout2 ({ state, commit }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('setToken', '')
          commit('setAccess', [])
          commit('setUserInfo','')
          localStorage.tagNavList=[];
          console.log(">>> login.js:logout2: 登出成功");
          resolve()
        }).catch(err => {
          console.log("登出失败");
          //resolve();
          reject(err)
        })
/*        console.log(">>> ................................");
        commit('setToken', '')
        commit('setAccess', [])
        localStorage.tagNavList=[];
        console.log(">>> login.js > logout2: 登出成功");
        resolve()*/
      })
    },
    /**
     * 切换登录单位
     * loginChangeOrg 在 api/login.js中
     */
    loginChangeOrg({state, commit},orgCode ){
      return new Promise((resolve, reject) => {
        loginChangeOrg(state.token,orgCode).then(res => {
          if (res.status === 200) {
            apiResult(res.data,false,result=>{
              let userInfo=result.data;
              commit('setLoginName', userInfo.loginName);
              commit('setUserName', userInfo.userName);
              commit('setUserCode', userInfo.userCode);
              commit('setFullName', userInfo.fullName);
              commit('setOrganizations', userInfo.organizations);
              commit('setUserInfo',userInfo);
            },err=>{
              reject(res.data.msg);
            })
            /*if (res.data.code === 0) {
              let userInfo=res.data.data;
              commit('setLoginName', userInfo.loginName);
              commit('setUserName', userInfo.userName);
              commit('setUserCode', userInfo.userCode);
              commit('setFullName', userInfo.fullName);
              commit('setOrganizations', userInfo.organizations);
              commit('setUserInfo',userInfo);
             //
            }else{
              console.log("切换登录机构失败");
              reject(res.data.msg);
            }*/
          }
          console.log("切换登录机构成功");
          resolve()
        }).catch(err => {
          reject(err)
        })
      })
    },

    /** 清附本地token */
    clearToken({state, commit}){
      commit('setToken', '')
      commit('setAccess', [])
      commit('setUserInfo','')
    },

    pushUserMessage({state,commit},message){
      commit('addUserMessage', message)
    },
    emptyUserMessage({state,commit}){
      commit('clearUserMessage')
    },

    getMapInfoFromApi(){

    },


  }
}
